<?php
namespace Common\Model;
use Think\Model;

class AdminModel extends Model{

	protected $trueTableName = 'admin';

	public $_validate = array(
		array('user','require','用户名必须填写'),
		array('password','require','密码必须填写'),
		array('code','require','验证码必须填写'),
	);


	public function checkCode($code){
		$verify = new \Org\Util\Verify();
		$bool = $verify->check($code);
		if($bool){
			return true;
		}else{
			return false;
		}
	}


	public function adminLogin(){
		//获取用户输入验证码
		$code = I('code');
		$bool = $this->checkCode($code);

		if($bool){
			//调用自动验证
			if(!$this->create()){
				//return false;
			}
			$user = I('post.user','','strip_tags');
			$password = I('post.password','','strip_tags');
			//定义要查询字段
			$condition['username'] = $user;
			//根据用户名查询用户信息
			$userInfo = $this->where($condition)->find();
			//如果查询返回不为空 就匹配账号密码
			if($userInfo){
				//是否管理员
				if($userInfo['is_admin'] == 1){
					//判断用户信息是否匹配
					if($userInfo['passwd'] == md5($password)){
						$key = sprintf('%s_aid',C('COOKIEVALIDATIONKEY'));
						$value = sprintf('%s_%s_%s',$userInfo['uid'],$userInfo['user_name'],md5($userInfo['user_name'].$userInfo['passwd'].'58shiyan'));
						$sValue = sprintf('%s_%s_%s',$userInfo['uid'],$userInfo['user_name'],$userInfo['passwd']);
						$userInfo['last_login'] = time();
						$this->save($userInfo);
						$_SESSION[$value] = $sValue;
						setcookie($key,$value, time()+3600*24*7);
						return true;
					}else{
						$this->error='用户名密码不正确';
						return false;
					}
				}else{
					$this->error='不是管理员,或权限不足';//不是管理员
					return false;
				}
			}else{
				$this->error='账号不存在';//账号不存在
				return false;
			}
		}else{
			$this->error='验证码不正确';
			return false;
		}		
	}

	public function editPassWord($userInfo){
		if(isset($userInfo[1]) && $userInfo[1]){
			$aid = $userInfo[0];
		}else{
			$this->error = '登录超时,请重新登录后修改密码';
			return false;
		}
		$pass = I('password');
		$pass2 = I('password2');
		if($pass == ''){
			$this->error = '密码不能为空';
			return false;
		}
		if($pass != $pass2){
			$this->error = '两次密码不一致';
			return false;
		}
		$password = md5($pass);
		$user = $this->find($aid);

		$user['passwd'] = $password;

		$this->save($user);
		return true;
	}

	public function getUserById($id){
		$map['id']= $id;
		return $this->where($map)->find();
	}
}
